package com.ma.imserver.netty.tcp.endecode;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ma.common.model.IMSendInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

public class MessageProtocolDecoder extends ReplayingDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() >= 4) {
            return;
        }
        //获取到包的长度
        long length = byteBuf.readLong();
        //转出IMSendInfo
        ByteBuf contentBuf = byteBuf.readBytes((int)length);
        String content = contentBuf.toString(CharsetUtil.UTF_8);
        IMSendInfo sendInfo = new ObjectMapper().readValue(content, IMSendInfo.class);
        list.add(sendInfo);
    }
}
